package com.zgs.mall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zgs.common.utils.R;
import com.zgs.mall.cart.feign.SkuFeignService;
import com.zgs.mall.cart.interceptor.CartInterceptor;
import com.zgs.mall.cart.service.CartService;
import com.zgs.mall.cart.vo.Cart;
import com.zgs.mall.cart.vo.CartItem;
import com.zgs.mall.cart.vo.SkuInfoVo;
import com.zgs.mall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private SkuFeignService skuFeignService;
    private String CART_PREFIX="mall:cart:";
    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        //获取购物项
        BoundHashOperations<String, Object, Object> boundHash =getCart();
        String s = (String) boundHash.get(skuId.toString());
        if (StringUtils.isEmpty(s)){
            CartItem cartItem =new CartItem();
            cartItem.setCount(num);
            //远程查询skuinfo
            CompletableFuture<Void> infoFuture = CompletableFuture.runAsync(() -> {
                R info = skuFeignService.info(skuId);
                SkuInfoVo infoVo = info.getData(new TypeReference<SkuInfoVo>() {
                });
                cartItem.setCheck(true);
                cartItem.setImage(infoVo.getSkuDefaultImg());
                cartItem.setPrice(infoVo.getPrice());
                cartItem.setTitle(infoVo.getSkuTitle());
            }, threadPoolExecutor);
            //远程查询sku销售属性
            CompletableFuture<Void> skuFuture = CompletableFuture.runAsync(() -> {
                R info = skuFeignService.getSkuSaleAttrValue(skuId);
                List<String> data = info.getData(new TypeReference<List<String>>() {
                });
                cartItem.setSkuAttr(data);
            }, threadPoolExecutor);
            try {
                CompletableFuture.allOf(skuFuture,infoFuture).get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            boundHash.put(""+skuId, JSON.toJSONString(cartItem));
            return cartItem;
        }else{
            CartItem cartItem = JSON.parseObject(s, CartItem.class);
            Integer count = cartItem.getCount();
            cartItem.setCount(count+num);
            boundHash.put(""+skuId, JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物车--购物项 存在redis中
     * @return
     */
    @Override
    public Cart getCartList() {
        UserInfoTo infoTo = CartInterceptor.local.get();
        Cart cart = new  Cart();
        Long userId = infoTo.getUserId();
        String cartKey=CART_PREFIX+infoTo.getUserKey();
        if(userId !=null){
            //登录状态下，把未登录时加入购物车的购物项加入加入到登录的购物车中
            List<CartItem> cartItems = getCartItems(cartKey);
            if (cartItems !=null && cartItems.size()>0){
                for (CartItem cartItem : cartItems) {
                    addToCart(cartItem.getSkuId(),cartItem.getCount());
                }
            }
            cartItems = getCartItems(CART_PREFIX+infoTo.getUserId());
            clearCart(cartKey);
            cart.setItems(cartItems);
        }else{
            //登录状态下，把未登录时加入购物车的购物项加入加入到登录的购物车中
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }
    public void clearCart(String cartKey){
        stringRedisTemplate.delete(cartKey);
    }

    /**
     * 获取当前用户所有被选中的购物项
     * @return
     */
    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo infoTo = CartInterceptor.local.get();
        if(infoTo==null){
            return null;
        }
        String cartKey="";
        if (infoTo.getUserId() !=null){
            cartKey=CART_PREFIX+infoTo.getUserId();
        }else{
            cartKey=CART_PREFIX+infoTo.getUserKey();
        }
        List<CartItem> cartItems = getCartItems(cartKey);

        //获取所有被选中的购物项
        List<CartItem> collect = cartItems.stream().filter(item -> {
            return item.getCheck();
        }).map(item->{
            //更新最新价格
            Long skuId = item.getSkuId();
            BigDecimal price = skuFeignService.getPrice(skuId);
            item.setPrice(price);
            return item;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public CartItem getCattItem(Long skuId) {
        BoundHashOperations<String, Object, Object> boundHashOperations = getCart();
        String o = (String)boundHashOperations.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    /**
     * 修改选中
     * @param itemId
     * @param check
     */
    @Override
    public void checkItem(Long itemId, Integer check) {
        BoundHashOperations<String, Object, Object> boundHashOperations = getCart();
        String o = (String) boundHashOperations.get(itemId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        cartItem.setCheck(check==1?true:false);
        String s = JSON.toJSONString(cartItem);
        boundHashOperations.put(itemId.toString(),s);
    }

    @Override
    public void countItem(Long itemId, Integer num) {
        BoundHashOperations<String, Object, Object> boundHashOperations = getCart();
        String o = (String) boundHashOperations.get(itemId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        boundHashOperations.put(itemId.toString(),s);
    }

    private BoundHashOperations<String, Object, Object> getCart() {
        UserInfoTo infoTo = CartInterceptor.local.get();
        String cartKey="";
        if (infoTo.getUserId() !=null){
            cartKey=CART_PREFIX+infoTo.getUserId();
        }else{
            cartKey=CART_PREFIX+infoTo.getUserKey();
        }
        BoundHashOperations<String, Object, Object> boundHash = stringRedisTemplate.boundHashOps(cartKey);
        return boundHash;
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> boundHash = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = boundHash.values();
        if (values!=null && values.size()>0){
            List<CartItem> collect = values.stream().map(obj -> {
                String s = (String) obj;
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
               // addToCart(cartItem.getSkuId(), cartItem.getCount());
                return cartItem;
            }).collect(Collectors.toList());
            return  collect;
        }
        return null;
    }
}
